package com.gewu.pm.other;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;

/**
 * 商品列表分割线装饰器
 */
public final class GoodsDividerDecoration extends RecyclerView.ItemDecoration {

    private final Paint mPaint;
    private final int mDividerHeight;

    public GoodsDividerDecoration() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mDividerHeight = 1;  // 1px
    }

    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int childCount = parent.getChildCount();
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        for (int i = 0; i < childCount - 1; i++) {  // 最后一项不画线
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDividerHeight;

            mPaint.setColor(ContextCompat.getColor(parent.getContext(), R.color.common_line_color));
            c.drawRect(left, top, right, bottom, mPaint);
        }
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int itemCount = parent.getAdapter() != null ? parent.getAdapter().getItemCount() : 0;
        
        // 最后一项不需要分割线偏移
        if (position < itemCount - 1) {
            outRect.set(0, 0, 0, mDividerHeight);
        }
    }
}

